package com.site.codegen.disposer.impl;

import com.alibaba.fastjson2.JSON;
import com.site.codegen.disposer.CommandDisposer;
import com.site.codegen.utils.DatabaseUtil;
import com.site.codegen.vo.DatasourceArgs;
import com.site.codegen.vo.DatasourceInfo;

import java.sql.Connection;
import java.sql.DatabaseMetaData;

public class DatasourceInfoDisposer implements CommandDisposer {
    @Override
    public Object dispose(String data) {
        DatasourceArgs datasourceArgs = JSON.parseObject(data, DatasourceArgs.class);
        Connection connection = null;
        DatasourceInfo datasourceInfo = new DatasourceInfo();

        try {
            connection = DatabaseUtil.getConnection(datasourceArgs.getDriverClass(), datasourceArgs.getUrl(), datasourceArgs.getUsername(), datasourceArgs.getPassword(), datasourceArgs.getDriverPath());
            DatabaseMetaData databaseMetaData = connection.getMetaData();
            String productName = databaseMetaData.getDatabaseProductName();
            String productVersion = databaseMetaData.getDatabaseProductVersion();
            String driverName = databaseMetaData.getDriverName();
            String driverVersion = databaseMetaData.getDriverVersion();
            boolean supportsFullOuterJoins = databaseMetaData.supportsFullOuterJoins();
            boolean supportsStoredProcedures = databaseMetaData.supportsStoredProcedures();
            boolean supportsTransactions = databaseMetaData.supportsTransactions();
            boolean supportsBatchUpdates = databaseMetaData.supportsBatchUpdates();
            String userName = databaseMetaData.getUserName();
//            System.out.println("数据库名称：" + productName);
//            System.out.println("数据库版本：" + productVersion);
//            System.out.println("驱动名称：" + driverName);
//            System.out.println("驱动版本：" + driverVersion);
            datasourceInfo.setDatabaseName(productName);
            datasourceInfo.setDatabaseVersion(productVersion);
            datasourceInfo.setDriverName(driverName);
            datasourceInfo.setDriverVersion(driverVersion);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return datasourceInfo;
    }
}
